package service

import (
	"github.com/gin-gonic/gin"
	"wx_build/core/msg"
	"wx_build/global"
	"wx_build/model/tables"
	"wx_build/utils"
)

type WxAppletService struct {
	tables.WxApplet
	Page   int    `json:"page"`
	Size   int    `json:"size"`
	Search string `json:"search"`
}

func (c *WxAppletService) Add(g *gin.Context) {
	app := tables.WxApplet{
		Appid: c.Appid,
	}
	err := app.QueryOne(&app)
	if err == nil {
		msg.Error(g, "小程序已存在", nil)
		return
	}
	err = c.WxApplet.Add(&c.WxApplet)
	if err != nil {
		msg.Error(g, "小程序添加失败", err)
		return
	}
	msg.Success(g, "小程序添加成功")
	return
}
func (c *WxAppletService) Update(g *gin.Context) {
	app := tables.WxApplet{
		Appid: c.Appid,
	}
	err := app.QueryOne(&app)
	if err != nil {
		msg.Error(g, "小程序不存在", err)
		return
	}
	if c.getProject() {
		msg.Error(g, "小程序已捆绑项目不允许编辑", err)
		return
	}
	app.PrivateKeyPath = c.PrivateKeyPath
	app.Name = c.Name
	db := global.Sqlite
	err = db.Save(&app).Error
	if err != nil {
		msg.Error(g, "编辑小程序失败", err)
		return
	}
	msg.Success(g, "编辑小程序成功")
	return

}
func (c *WxAppletService) List(g *gin.Context) {
	list := new([]tables.WxApplet)
	var count int64
	db := global.Sqlite
	if c.Search != "" {
		db = db.Where("name LIKE ?", "%"+c.Search+"%")
	}
	db.Where(c.WxApplet).Find(&list).Count(&count)
	db.Where(c.WxApplet).Order("created_at desc").Limit(c.Size).Offset((c.Page - 1) * c.Size).Find(&list)
	data := make([]map[string]interface{}, len(*list))
	for k, v := range *list {
		item, _ := utils.ToMap(v)
		data[k] = item
	}
	res := make(map[string]interface{})
	res["count"] = count
	res["list"] = data
	msg.Success(g, "查询成功", res)
	return
}
func (c *WxAppletService) Delete(g *gin.Context) {
	app := tables.WxApplet{
		Appid: c.Appid,
	}
	err := app.QueryOne(&app)
	if err != nil {
		msg.Error(g, "小程序不存在", err)
		return
	}
	if c.getProject() {
		msg.Error(g, "该小程序下面还有项目存在，请先删除项目", nil)
		return
	}
	db := global.Sqlite
	err = db.Delete(&app).Error
	if err != nil {
		msg.Error(g, "删除小程序失败", err)
		return
	}
	msg.Success(g, "删除小程序成功")
	return
}

// 删除小程序的时候判断小程序下面是否有项目，如果有则不能删除
func (c *WxAppletService) getProject() bool {
	project := tables.Project{
		Appid: c.Appid,
	}
	err := project.QueryOne(&project)
	if err != nil {
		return false
	} else {
		return true
	}
}
func (c *WxAppletService) QueryAll(g *gin.Context) {
	list := new([]tables.WxApplet)
	db := global.Sqlite
	db.Find(&list)
	data := make([]map[string]interface{}, len(*list))
	for k, v := range *list {
		item, _ := utils.ToMap(v)
		data[k] = item
	}
	msg.Success(g, "查询成功", data)
	return
}
